package com.gexin.model.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.gexin.common.utils.StringUtil;
import com.gexin.model.system.base.BaseAdminUserRole;
import com.jfinal.plugin.activerecord.Db;

/**
 * 业务名称:  t_admin_user_role(用户权限关系) 
 */
@SuppressWarnings("serial")
public class AdminUserRole extends BaseAdminUserRole<AdminUserRole> {
	public static final AdminUserRole dao = new AdminUserRole();
	
	
	
	public Map<String, String>  getUserRoleCode(Integer  user_id){
		Map<String, String>   map  =new HashMap<String, String>();
		List<AdminUserRole>    list = find("select rel.role_id,role.role_code from  t_admin_user_role as rel LEFT JOIN  t_admin_role  as role on rel.role_id=role.id    where rel.user_id=?",user_id);
		for(AdminUserRole  r :  list){
			map.put(r.getStr("role_code"), r.getRoleId()+"");
		}
		return  map;
	}
	
	
	public Map<String, String>  getUserRole(Integer  id){
		Map<String, String>   map  =new HashMap<String, String>();
		List<AdminUserRole>    list = find("select * from  t_admin_user_role  where user_id=?",id);
		for(AdminUserRole  r :  list){
			map.put(r.getRoleId()+"", r.getUserId()+"");
		}
		return  map;
	}
	/**
	 * 保存用户的多个权限id
	 * @param user_id
	 * @param roles
	 */
	public void saveUserRole(Integer user_id,String roles[]){
		Db.update("DELETE from t_admin_user_role where user_id=?",user_id);
		List<AdminUserRole> list  =new ArrayList<AdminUserRole>();
		for(String  item  : roles){
			if(StringUtil.isNotBlank(item)){
				AdminUserRole userRole =new AdminUserRole();
				userRole.setRoleId(Integer.parseInt(item));
				userRole.setUserId(user_id);
				list.add(userRole);
			}
		
		}
		Db.batchSave(list, list.size());
	}
	
	
	public List<AdminUserRole> getRoleIds(Integer user_id) {
		return dao.find("select role_id from t_admin_user_role where user_id=?",user_id);
	}
	
	/**
	 * 根据用户id拼接该用户对应的全部权限名称
	 * @param user_id
	 * @return
	 */
	public String getRoleNames(Integer user_id) {
		StringBuffer names= new StringBuffer("");
		List<AdminUserRole> list = dao.find("select * from t_admin_user_role where user_id=?",user_id);
		if (list.size()>0) {
			for (int i = 0; i < list.size(); i++) {
				if (i==list.size()-1) {
					names.append(AdminRole.dao.findById(list.get(i).getInt("role_id")).getName());
					break;
				}
				names.append(AdminRole.dao.findById(list.get(i).getInt("role_id")).getName()+"，");
			}
			
		}
		return names.toString();
	}
	
	
}
